<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #snakeHead {
            background: red;
        }

        .snake {
            background: aqua;
            width: 40px;
            height: 40px;
            position: absolute;
            border-radius: 50%;
        }

        .board {
            margin-left: 150px;
            margin-top: 150px;
            outline: 2px solid red;
            width: 800px;
            height: 400px;
            position: relative;
        }
    </style>
</head>
<body>
<section id="board" class="board">
    <div class="snake" id="snakeHead"></div>
    <div class="snake"></div>
    <div class="snake"></div>
    <div class="snake"></div>
    <div class="snake"></div>
    <div class="snake"></div>
</section>
<script>
    let boardWidth, boardHeight, width, height;
    onload = () => {
        let board = document.querySelector('#board');
        let snakes = document.querySelectorAll('.snake');
        boardWidth = board.offsetWidth;
        boardHeight = board.offsetHeight;
        width = snakes[0].offsetWidth;
        height = snakes[0].offsetHeight;
        document.onkeydown = (ev) => {

            snakeBodyMove();

            snakeHeadMove(ev, snakes[0]);
        }
    }

    function snakeBodyMove() {
        let snakes = document.querySelectorAll(".snake");

        for (let i = snakes.length - 1; i > 0; i--) {
            snakes[i].style['left'] = snakes[i - 1].style['left'];
            snakes[i].style['top'] = snakes[i - 1].style['top'];

        }
    }
    function snakeHeadMove(ev, snakeHead) {
        let left = snakeHead.offsetLeft;
        let top = snakeHead.offsetTop;
        switch (ev.key) {
            case 'ArrowUp':
                if (top <= 0) return;
                snakeHead.style['top'] = top - height + 'px';
                break;
            case 'ArrowLeft':
                if (left <= 0) return;
                snakeHead.style['left'] = left - width + 'px';
                break;
            case 'ArrowDown':
                if (top >= boardHeight - height) return;
                snakeHead.style['top'] = top + height + 'px';
                break;
            case 'ArrowRight':
                if (left >= boardWidth - width) return;
                snakeHead.style['left'] = left + width + 'px';
                break;
        }
    }
</script>
</body>
</html>